import React, { useState } from 'react';
import styles from './teamScore.less';
import { DatePicker, Button, Input, Table, Form, Select, Spin } from 'antd';
import { Link } from 'react-router-dom';
import request from '@/http';
import qs from 'qs';
const { RangePicker } = DatePicker;
const { Option } = Select;

export default () => {
  const [formObject] = Form.useForm();

  const [dataSource, setDataSource] = React.useState<any[]>([]);
  const [loadingState, setLoadingState] = React.useState({ loading: true });
  const [pagination, setPagination] = React.useState({
    current: 1,
    total: 20,
    pageSize: 10,
    showSizeChanger: true,
    pageSizeOptions: ['10', '50', '200', '500'],
    showQuickJumper: true,
  });
  const loadDataSource = async (
    userParams: any,
    pageValue: any,
    pageSize: any,
  ) => {
    const ds = {
      ...userParams,
      current: pageValue ? pageValue : 1,
      size: pageSize ? pageSize : 5,
    };

    const result: any = await request.post(
      '/api/admin/adminScore/getTeamScorePage',
      qs.stringify(ds),
    );

    console.log('小组评分：', result);
    if (result && result.code === 200) {
      const data: any = result.data.records.map((user: any) => ({
        key: `user_${user.id}`,
        id: user.id, // 小组id
        collegesName: user.collegesName, //	院系名
        courseId: user.courseId, //	院系Id
        teamId: user.teamId, //	小组Id
        studentNumbers: user.studentNumbers, //		小组成员数量
        majorName: user.majorName, //	院系名
        responsibilityTeacher: user.responsibilityTeacher, //	责任老师名
        teamName: user.teamName, //	小组名
        courseName: user.courseName, //		项目名称
        teamLeader: user.teamLeader, //	小组组长
        score: user.score, //		小组综合得分
        comments: user.comments,
      }));

      const newPageObject = {
        ...pagination,
        current: pageValue,
        size: pageSize,
        total: result.records, //总条数 分页               *******************
      };

      setPagination(newPageObject);
      setDataSource(data);
      setLoadingState({ loading: false });
      // console.log(data)
    }
  };

  const [cCourseNameData, setCCourseNameData] = useState<any[]>([]);
  const getCourseName = async () => {
    //项目名称
    const chooseCourse: any = await request.get('/queryAllCourseStatus?');
    const cCourse = chooseCourse.map((user: any) => ({
      key: `user_${user.courseId}`,
      id: user.courseId,
      courseId: user.courseId,
      courseName: user.courseName,
    }));
    sessionStorage.setItem('courseName', JSON.stringify(cCourse));
    let courseName = localStorage.getItem('courseName');
    if (courseName) {
      setCCourseNameData(JSON.parse(courseName));
    }
  };

  const [cGroupData, setCGroupData] = useState<any[]>([]);
  const getGroup = async () => {
    const chooseMajor: any = await request.get('/queryAllGroup');
    const cMajor = chooseMajor.map((user: any) => ({
      key: `user_${user.groupId}`,
      id: user.groupId,
      groupId: user.groupId,
      teamName: user.teamName,
    }));
    localStorage.setItem('major', JSON.stringify(cMajor));
    let major = localStorage.getItem('major');
    if (major) {
      setCGroupData(JSON.parse(major));
    }
  };

  //搜索
  const searchOnClick = async () => {
    setLoadingState({ loading: true });
    console.log(formObject.getFieldsValue());
    const data = await formObject.validateFields();
    var dataStr = '';
    var ds = {
      ...data,
    };
    console.log(data);
    for (var n in ds) {
      if (dataStr != '') dataStr += '&';
      dataStr += encodeURIComponent(n) + '=' + encodeURIComponent(ds[n]);
    }

    await loadDataSource(data, 1, pagination.pageSize);
  };

  //生命周期函数
  React.useEffect(() => {
    loadDataSource(null, 1, pagination.pageSize).finally();
    // getCourseName();
    // getGroup();
  }, []);

  //换页
  const pageOnChange = async (page: any) => {
    await loadDataSource(
      formObject.getFieldsValue(),
      page.current,
      page.pageSize,
    );
  };
  return (
    <div className="pageMain">
      <div className="pageContent">
        <div className="search" style={{ width: '1200px', height: '120px' }}>
          <div className={styles.searchForm}>
            <Form layout="inline">
              <Form.Item label="项目名称" name="courseName" initialValue="">
                <Select className="teamScoreSelect">
                  <Option value="">请选择...</Option>
                  {cCourseNameData
                    ? cCourseNameData.map((item: any, index: any) => {
                        return (
                          <Option
                            index={index}
                            key={index}
                            value={item.courseName}
                            children={item.courseName}
                          />
                        );
                      })
                    : ''}
                </Select>
              </Form.Item>

              <Form.Item label="小组名称" name="teamName" initialValue="">
                <Select className="teamScoreSelect">
                  <Option value="">请选择...</Option>
                  {cGroupData
                    ? cGroupData.map((item: any, index: any) => {
                        return (
                          <Option
                            index={index}
                            key={index}
                            value={item.teamName}
                            children={item.teamName}
                          />
                        );
                      })
                    : ''}
                </Select>
              </Form.Item>

              <Form.Item>
                <Button type="primary">查询</Button>
                <Button
                  style={{ margin: '0 8px' }}
                  onClick={() => {
                    formObject.resetFields();
                  }}
                >
                  重置
                </Button>
              </Form.Item>
            </Form>
          </div>
        </div>

        <div className={styles.mainTable}>
          <Spin tip="Loading..." spinning={loadingState.loading}>
            <Table
              columns={[
                {
                  title: '院系',
                  dataIndex: 'collegesName',
                  key: 'collegesName',
                  width: 75,
                  align: 'center',
                },

                {
                  key: 'teamId',
                  width: 0.0001,
                  align: 'center',
                },
                {
                  key: 'courseId',
                  width: 0.0001,
                  align: 'center',
                },
                {
                  key: 'comments',
                  width: 0.0001,
                  align: 'center',
                },

                {
                  title: '项目名称',
                  dataIndex: 'courseName',
                  key: 'courseName',
                  width: 100,
                  align: 'center',
                },
                {
                  title: '责任老师',
                  dataIndex: 'responsibilityTeacher',
                  key: 'responsibilityTeacher',
                  width: 75,
                  align: 'center',
                },
                {
                  title: '小组',
                  dataIndex: 'teamName',
                  key: 'teamName',
                  width: 75,
                  align: 'center',
                },
                {
                  title: '小组长 ',
                  dataIndex: 'teamLeader',
                  key: 'teamLeader',
                  width: 75,
                  align: 'center',
                },
                {
                  title: '小组成员',
                  dataIndex: 'studentNumbers',
                  key: 'studentNumbers',
                  width: 75,
                  align: 'center',
                },
                {
                  title: '综合得分',
                  dataIndex: 'score',
                  key: 'score',
                  width: 75,
                  align: 'center',
                },

                {
                  title: '操作',
                  key: 'action',
                  align: 'center',
                  width: 100,
                  render: (row: any) => (
                    <>
                      <Link to={{ pathname: 'tsDetail', state: { ...row } }}>
                        <Button type="link">查看详情</Button>
                      </Link>
                    </>
                  ),
                },
              ]}
              dataSource={dataSource}
              pagination={pagination}
              onChange={pageOnChange}
              tableLayout="fixed"
              bordered
            />
          </Spin>
        </div>
      </div>
    </div>
  );
};
